# -*- coding: utf-8 -*-
"""
******* 文档说明 ******


# 当前项目: ServerAPI_Demo
# 创建时间: 2021-01-08  11:12
# 开发作者: Vincent
# 版    本: V1.0
"""
import time
import os
import flask
from flask import request, Flask

start_time = time.strftime('%Y%m%d %H:%M:%S', time.localtime(time.time()))

app = Flask(__name__)

print('Flask Version:{} '.format(flask.__version__))
print('CWD:{} '.format(os.path.abspath(os.path.dirname(__file__))))  # 当前路径


# 参数传输测试  UTF-8 编码格式
@app.route('/text', methods=['POST'])
def text():
    print('----------------------------------------------')
    print('{:12s}: {}'.format('Method', request.method))
    print('{:12s}: {}'.format('URL', request.url))
    print('{:12s}: {}'.format('params', request.args))
    print('{:12s}: {}'.format('Header', request.headers))
    print('{:12s}: {}'.format('Form', request.form))
    print('{:12s}: {}'.format('Data', request.data))
    print('{:12s}: {}'.format('JSON', request.json))

    print('\n\n', request.data.decode('utf-8'))
    return request.data


# 参数传输测试  JSON 格式  UTF-8 编码格式
@app.route('/json_data', methods=['POST'])
def json_data():
    print('----------------------------------------------')
    print('{:12s}: {}'.format('Method', request.method))
    print('{:12s}: {}'.format('URL', request.url))
    print('{:12s}: {}'.format('params', request.args))
    print('{:12s}: {}'.format('Header', request.headers))
    print('{:12s}: {}'.format('Form', request.form))
    print('{:12s}: {}'.format('Data', request.data))
    print('{:12s}: {}'.format('JSON', request.json))

    import json
    print('\n\n', json.dumps(json.loads(request.data), ensure_ascii=False, indent=4, sort_keys=True))

    return request.data


# API 状态监测
@app.route('/health', methods=['POST', 'GET'])
def health():
    print('health test.')
    current_time = time.strftime('%Y%m%d %H:%M:%S', time.localtime(time.time()))
    return 'Start: {} ........... Status: <OK> ........... Time: {}'.format(start_time, current_time)


# ##########################################################################################
# 后台监控线程。 在系统中可作为后台定时任务线程，如模型更新、心跳、服务监测等
import time
import threading
from datetime import datetime
from threading import Timer


# 定时任务
class Crontab(object):
    def __init__(self):
        self.num = 1

    # 循环体主程序
    def task_main(self):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), self.num)
        self.num += 1

    # 轮询代码
    def _polling(self, polling_time):
        """
        :param polling_time:  轮询时间间隔  second
        :return:
        """

        # ################## 循环体主程序 ###########################
        self.task_main()
        # ###########################################################

        # 达到指定条件 停止定时任务
        if self.num > 50:
            return
        # ###########################################################

        t = Timer(polling_time, self._polling, (polling_time,))
        t.start()

    def run(self):
        # 开启定时任务， 间隔为 10 Second
        self._polling(10)


# 后台监控进程
class BackstageThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.stop_event = threading.Event()

        # 运行状态标志位
        self.flag = True

        self.num = 1

    def stop(self):
        self.stop_event.set()

    # 启动程序
    def run(self):
        # 开始运行定时任务
        Crontab().run()

        # # 循环监控，可使用定时器替换
        # while True:  # 可使用开关替换
        #
        #     if self.flag:
        #         print('后台进程：{}   {}'.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), self.num))
        #
        #         self.num += 1
        #         time.sleep(10)

    def pause(self):
        print('Pause!!!')
        self.flag = False

    def play(self):
        print('Play !!!')
        self.flag = True


if __name__ == '__main__':
    # 后台监控进程，可用来判断数据库等服务是否异常
    bt = BackstageThread()
    bt.start()

    # 启动API服务
    app.run(host='0.0.0.0', port=8888, debug=False)
